package com.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import util.Util;

import com.packages.ClientPackageHandler;
import com.packages.ServerPackageHandler;

public class ServerMain {
	
	/**
	 * Starts up the server side.
	 * @param args
	 */
	public static void main(String[] args)
	{
		try
		{
			int id = 0;
			ClientPackageHandler cph = new ClientPackageHandler();
			ServerPackageHandler sph = new ServerPackageHandler();
			UserPackageFilter upf = new UserPackageFilter();
			ServerSocket ss = new ServerSocket(30000);
			RoomHandler rh = new RoomHandler();
			Monitor m = new Monitor();

			rh.createRoom("Hemmarummet", Util.SHA1("ojoj"));
			rh.createRoom("Testrum", Util.SHA1("hejs"));
			rh.createRoom("Softrum", Util.SHA1("wtf"));
			rh.createRoom("SUPSUPSUPRum", Util.SHA1("nah"));

			while (true)
			{
				Socket s = ss.accept();
				System.out.println("Server accepted connection, givin id: " + id);
				if (!m.registerClient(id))
				{
					System.out.println("Failed to register client");
				} else
				{
					new OutputStreamHandler(s, m, id).start();
					new InputStreamHandler(s, m, id).start();
					new MessageHandler(m, rh, cph, sph, id, upf).start();
					upf.registerClient(id);
					id++;
				}
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}
